package net.midnighttd.engine.map;

import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import java.util.ArrayList;
import net.midnighttd.engine.ResourceManager;

/**
 * Author: Adam Scarr
 * Date: 17/04/2009
 * Time: 7:19:14 PM
 */
public class Map extends ArrayList<ArrayList<Tile>> {
    private Tileset tileset;

    public Map(Element e) {
        loadFromXML(e);
    }

    public void loadFromXML(Element e) {
        tileset = new Tileset(ResourceManager.getXML(e.getAttribute("tileset")));

        NodeList rows = e.getElementsByTagName("row");

        for(int y = 0; y < rows.getLength(); y++) {
            Element row = (Element)rows.item(y);

            ArrayList<Tile> newRow = new ArrayList<Tile>();

            NodeList cells = row.getElementsByTagName("cell");
            for(int x = 0; x < cells.getLength(); x++) {
                Element cell = (Element)cells.item(x);

                newRow.add(tileset.get(cell.getTextContent()));
            }

            add(newRow);
        }
    }

    public int getWidth() {
        assert(size() > 0);

        return get(0).size();
    }

    public int getHeight() {
        return size();
    }

    public Tile get(int x, int y) {
        assert(x >= 0);
        assert(y >= 0);
        assert(x < getWidth());
        assert(y < getHeight());

        return get(y).get(x);
    }

    public boolean inBounds(int x, int y) {
        return x >= 0 && y >= 0 && x < getWidth() && y < getHeight();
    }

    public Tileset getTileset() {
        return tileset;
    }
}
